package com.kdtech.analyse.outside;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @name 新加坡海峡时报
 * @link http://www.straitstimes.com/global
 * @author dhy
 */
public class StraitstimesOutsideAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.straitstimes.com/[a-z]*/[a-z\\-]*",
		"http://www.straitstimes.com/[a-z]*/[a-z]*-[a-z]*/[a-z\\-]*",
		"http://www.straitstimes.com/[a-z]*/[a-z]*/[a-z\\-]*",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title =doc.select("h1.headline").text();
		
		doc.select("div.label-inline").remove();
		date = DateUtils.matchDate(doc.select("div.story-postdate").text());
		if(date==null)
		{
			String dateStr = doc.select("div.story-postdate").text();
			Matcher matcher = Pattern.compile("([0-9]+) hours ago").matcher(dateStr);
			if(matcher.find())
			{
				try
				{
					int hour = Integer.parseInt(matcher.group(1));
					date = System.currentTimeMillis() - hour * 60 * 60 * 1000;
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		
		content=HtmlCleaner.getContentHtml(url,doc.select("div.field-item"));
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	

	

	
}
